App.controller("addCountCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	var params = JSON.parse($stateParams.params);
	console.log("路由参数：",params);
	$scope.form = {};			//表单
	$scope.form.userInfoEntity = {};   	 	//用户信息
	$scope.form.commerceEntity = {};   	    //工商注册信息
	$scope.form.userPermissionEntity = [];  //权限信息
	
	$scope.logo_show = true;				//LOGO（显示）
	$scope.coordinate_show = false;			//坐标（显示）
	$scope.commerce_show = true;			//工商信息（显示
	$scope.moduleContainer_show = false;	//功能权限（显示）
	$scope.submit_show = true;				//提交（显示）
	$scope.resetPassword_show = true;		//密码重置（显示）
	var moduleTree = null		//模块树;		
	var functionMenu = null;	//功能菜单; 
	
	var shopUserInfo = {};	//商户信息
	
	var limitParam = {imageSize:80, format:"jpg"};		//封面图
	var mapObj = null;  //地图对象
	var alertModel = {};	//alert模态框
	
	
	//初始化地图
	$scope.initMap = function(mapContainerId,searchLocationId,searchCoordinateId){
		mapObj = new AMap.Map(mapContainerId, {    //地图加载
	        resizeEnable: true,
	        zoom:11,
	        center: [116.397428, 39.90923]
	    });
	    var autoOptions = {    //输入提示
	        input: searchLocationId
	    };
	    var auto = new AMap.Autocomplete(autoOptions);
	    var placeSearch = new AMap.PlaceSearch({   //构造地点查询类
	        map: mapObj
	    });  
	    
	    AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
	    function select(e) {
	        placeSearch.setCity(e.poi.adcode);
	        placeSearch.search(e.poi.name);  //关键字查询查询
	    }
	    mapObj.plugin(["AMap.ToolBar"], function() {  //地图工具条
	    	mapObj.addControl(new AMap.ToolBar());
		});

	    mapObj.on('click', function(e) {	//维度，经度
			$("#"+searchCoordinateId).val(e.lnglat.getLat()+","+e.lnglat.getLng());
	    });
	}
	
	//获取菜单
	$scope.getMenu = function(checkedDataList){
		$http({
			   url: path+'/server/getpermissionall',
			   method: 'GET'  
		}).success(function(data){
			if(data.code==0){
				functionMenu = data.result;
				functionMenu = $scope.packZtreeDataForChecked(functionMenu,checkedDataList);
				
				moduleTree = publicService.initZtree("ztree1",functionMenu);
			}else{
				console.log("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//封装选中的树形插件数据
	$scope.packZtreeDataForChecked = function(allData,checkedData){
		$.each(allData, function(index, OneObj){
			if(checkedData && checkedData.length>0){
				if(publicService.isExitInArray(checkedData,"permission_id",OneObj.id)){
					OneObj.checked = true;
				}
			}
		});
		
		return allData;
	}
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	//检测不包含中文
	$scope.checkNotContainChinese = function(type){
		var value = '';
		if(type==1){
			value = $scope.form.account;
		}else if(type==2){
			value = $scope.pwd1;
		}
		
		if(value && publicService.checkIsContainChinese(value)){
			$scope.alertMessage("不应该包含中文！");
			if(type==1){
				$scope.form.account = shopUserInfo.account;
			}else if(type==2){
				$scope.pwd1 = '';
			}
		}
	}
	
	//检测账号
	$scope.checkAccount = function(){ 
		if($scope.form.account && params.method!="look"){  //有值
			var postData = {
					account: $scope.form.account
			};
			
			$http({
				   url:	path+'/server/checkuser',
				   method: 'POST',   
				   data: angular.toJson(postData),  
			}).success(function(data){
				if(data.code==0){  //成功
					
				}else if(data.code==1){  //失败
					$scope.alertMessage("用户已存在，请重新录入！");
					$scope.form.account = shopUserInfo.account;
				}
			}).error(function(data){
				alert(data);   
			})
		}
	}
	
	//重置密码
	$scope.resetPassword = function(){ 
		$http({
			   url:	path+'/server/resetpassword/'+shopUserInfo.id,
			   method: 'GET'   
		}).success(function(data){
			if(data.code==0){  //成功
				$scope.pwd1 = "888888";
				$scope.form.pwd =$scope.pwd1;  // 
			}else if(data.code==1){  //失败
				
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//表单提交
	$scope.formSubmit = function(){
		if(params.method=="add"){
			$scope.form.pwd =$scope.pwd1
		}
		$scope.form.userInfoEntity.imgurl = $("#logo_url").val();		//LOGO
		$scope.form.userInfoEntity.transpond_imgurl = $("#logo_aother_url").val();
		
		var codeString = $("#province").data("kendoComboBox").value()
						+","
						+$("#city").data("kendoComboBox").value()
						+","
						+$("#area").data("kendoComboBox").value();
		$scope.form.userInfoEntity.region_code = codeString;
		
		//工商信息
		$scope.form.commerceEntity.biz_url = $("#upload1_url").val();  
    	
		$scope.form.state = $("#checkState").data("kendoDropDownList").value();		//审核状态

		if(!$scope.form.userInfoEntity.name){
			$scope.alertMessage("请输入【商户名称】！");
			return;
		}
		if(!$scope.form.userInfoEntity.principal){
			$scope.alertMessage("请输入【负责人】！");
			return;
		}
		if(!$scope.form.userInfoEntity.phone_num){
			$scope.alertMessage("请输入【联系方式】！");
			return;
		}
		if(!$scope.form.organization_code){
			$scope.alertMessage("请输入【组织编号】！");
			return;
		}
		if($scope.form.user_level==1 && !$scope.form.department_code){
			$scope.alertMessage("请输入【部门编号】！");
			return;
		}
		if(userInfo.user_level==0 && !$scope.form.userInfoEntity.imgurl){
			$scope.alertMessage("请上传【LOGO】！");
			return;
		}
		if(!$("#area").data("kendoComboBox").value()){
			$scope.alertMessage("请选择【所在属性地址】！");
			return;
		}
		if(!$scope.form.userInfoEntity.addr){
			$scope.alertMessage("请输入【详细地址】！");
			return;
		}
		if(params.userLevel==1){
			$scope.form.userInfoEntity.lbs = $("#search_coordinate").val();
			if(!$scope.form.userInfoEntity.lbs){
				$scope.alertMessage("请在地图上选择【商户位置】！");
				return;
			}
		}
		if(!$scope.form.account){
			$scope.alertMessage("请输入【账号】！");
			return;
		}
		if(!$scope.pwd1){
			$scope.alertMessage("请输入【密码】！");
			return;
		}
		if(userInfo.user_level==0 && !$scope.form.commerceEntity.biz_url){
			$scope.alertMessage("请上传【营业执照】！");
			return;
		}
		if(userInfo.user_level==0 && !$scope.form.commerceEntity.biz_num){
			$scope.alertMessage("请输入【营业执照注册号】！");
			return;
		}
		if(userInfo.user_level==0 && $scope.moduleContainer_show){	//开发者
    		//功能权限
        	var checkedNodes = moduleTree.ztree.getCheckedNodes(true);
        	$.each(checkedNodes, function(index, OneObj){
    			var moduleObj = {
    					permission_id: OneObj.id
    			};
    			$scope.form.userPermissionEntity.push(moduleObj);
    		});
        	if($scope.form.userPermissionEntity.length==0){
    			$scope.alertMessage("请选择【功能权限】！");
    			return;
    		}
    	}
		
		var url = '';
		if(params.method=="add"){
			url = path+'/server/createuser';
		}else if(params.method=="edit"){
			url = path+'/server/modifyuser';
			$scope.form.id = shopUserInfo.id;
		}
		
		$http({
			   url: url,
			   method: 'POST',
			   data: angular.toJson($scope.form),  
		}).success(function(data){
			if(data.code=='0'){
				$scope.alertMessage("成功！");
				$location.path("/accountManagement");
			}else if(data.code=='1'){
				$scope.alertMessage("失败！");
			}else if(data.code=='2'){
				$scope.alertMessage(data.message);
			}else if(data.code=='3'){
				$scope.alertMessage(data.message);
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//获取用户信息
	$scope.getUserInfo = function(id){
		$http({
			   url: path+'/server/getuser/'+id,
			   method: 'GET'  
		}).success(function(data){
			if(data.code==0){
				shopUserInfo = data.result;
				
				$scope.form.id = shopUserInfo.id;
				$scope.form.userInfoEntity.id = shopUserInfo.userInfoEntity.id;
				$scope.form.commerceEntity.id = shopUserInfo.commerceEntity.id;
				$scope.form.userInfoEntity.name = shopUserInfo.userInfoEntity.name;
				$scope.form.userInfoEntity.principal = shopUserInfo.userInfoEntity.principal;
				$scope.form.userInfoEntity.phone_num = shopUserInfo.userInfoEntity.phone_num;
				
				$scope.form.organization_code = shopUserInfo.organization_code;  //组织编号
				$scope.form.department_code = shopUserInfo.department_code;  //部门编号
				publicService.showUploadImage("logo_img","logo_url",shopUserInfo.userInfoEntity.imgurl);
				//省，市，区
				var codeArr = shopUserInfo.userInfoEntity.region_code.split(",");
				$("#province").data("kendoComboBox").value(codeArr[0]);
				publicService.getCityData(1,codeArr[0],codeArr[1]);
				$timeout(function(){
					publicService.getAreaData(1,codeArr[1],codeArr[2]);
			    }, 300);
				
				if(shopUserInfo.user_level==1){	//一级用户
					//$('#province').data("kendoComboBox").readonly(true);
					
					$scope.coordinate_show = true;
					//设置地图中心位置
					$("#search_coordinate").val(shopUserInfo.userInfoEntity.lbs);
					var coordinateArr = shopUserInfo.userInfoEntity.lbs.split(",");
					var coordinateArr_1 = [Number(coordinateArr[1]),Number(coordinateArr[0])];
					mapObj.setCenter(coordinateArr_1);
					// 在新中心点添加 marker 
			        var marker = new AMap.Marker({
			            map: mapObj,
			            position: coordinateArr_1
			        });
				}
				
				$scope.form.userInfoEntity.addr = shopUserInfo.userInfoEntity.addr;
				
				$scope.form.account = shopUserInfo.account;
				$scope.pwd1 = "******";
				//工商注册信息
				publicService.showUploadImage("upload1_img","upload1_url",shopUserInfo.commerceEntity.biz_url);
				$scope.form.commerceEntity.biz_num = shopUserInfo.commerceEntity.biz_num;
				//功能权限
				$scope.getMenu(shopUserInfo.userPermissionEntity);		//获取菜单
				//审核状态
				$("#checkState").data("kendoDropDownList").value(shopUserInfo.state);
			}else{
				console.log("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//显示默认的省份
	$scope.showDefaultProvince = function(code){
		$("#province").data("kendoComboBox").value(code);
		$('#province').data("kendoComboBox").readonly(true);
		publicService.getCityData(1,code);
	}
	//获取组织编号
	$scope.getStoreInfo = function(){
		var formData = new FormData($('#organization')[0]);
		var paths = path+'/server/selectZzhInfo';
		if($scope.form.organization_code){
		    $.ajax({
			      url: paths,
			      type: "POST",
			      data: formData,
			      async:false,
				  cache: false,	//无缓存
				  contentType: false,
				  processData: false,	//不需要对数据做处理
			      success: function (rsData) { 
			    	  if(rsData.code =='0'){
				    	  if(rsData.result){
					   			 $scope.form.userInfoEntity.name =  rsData.result.orgName;  //属性名称
								 $scope.form.userInfoEntity.addr = rsData.result.orgAddr;  //地址
								 $scope.form.userInfoEntity.principal = rsData.result.orgLinker;   //负责人
								 $scope.form.userInfoEntity.phone_num = rsData.result.orgTel;   //电话
					    	}else{
					    		alert('无法获取用户信息！');
					    	}
			    	  }else  if(rsData.code =='1'){
			    		  alert('接口出错！请联系开发者！');
			    	  }


				    },
				    error: function (XmlHttpRequest, textStatus, errorThrown) {
				        alert('系统异常！');
				    }
			    });
			    $scope.departmentAndorganization();
		}

	};
	//部门编号失去焦点
	$scope.verifys = function(){
		$scope.departmentAndorganization();
	};
	//组织编号和部门编号的验证(两个都填了)
	$scope.departmentAndorganization = function(){
		if($scope.coordinate_show&&$scope.form.department_code&&$scope.form.organization_code){
			$scope.verify_show = true;
		}else{
			$scope.verify_show = false;
		}
	}
	//获取部门编号
	$scope.getdepartInfo = function(){
		var formData = new FormData($('#organization')[0]);
	    $.ajax({
		      url:  path+'/server/selectBmhInfo',
		      type: "POST",
		      data: formData,
			  cache: false,	//无缓存
			  async:false,
			  contentType: false,
			  processData: false,	//不需要对数据做处理
		      success: function (rsData) { 
		    	  if(rsData.code=='0'){
		    		  if(rsData.result){
		    			  $(".otherHide").removeAttr("readonly");
		    			$scope.form.userInfoEntity.name =  rsData.result.depName;  //属性名称
		    			 $scope.form.userInfoEntity.addr = rsData.result.depAddr;  //地址
		    			 $scope.form.userInfoEntity.principal = rsData.result.depLinker;   //负责人
		    			 $scope.form.userInfoEntity.phone_num = rsData.result.depTel;   //电话
		    			 
		    		  }else{
		    			  alert("无法获取用户信息！");
		    		  }
		    	  }else if(rsData.code=='1'){
		    		  alert('接口失败！请联系开发！');
		    	  }
		    	 
			    },
			    error: function (XmlHttpRequest, textStatus, errorThrown) {
			        alert('系统异常！');
			    }
		    });
	}
	//更改组织编号部门编号
	$scope.changesCode = function(type){
		var contents1 = $scope.form.organization_code.length;
		var contents2 = $scope.form.department_code.length;
		if(type ==1&&$scope.coordinate_show&&contents1==0||type ==2&&contents2==0){
			$scope.verify_show = false;
			$(".otherHide").val('');
			$(".otherHide").attr("readonly","readonly");
		}                                                                                                                                                                                                                                                                                                                                                                                             
	}
	//上传图片（单个）
	$scope.uploadImage = function(containerId,imgId,imgUrlId,limitParam){
		var uploadUrl = path+"/common/uploadUserLogo";
		if(params.userLevel==3){
			uploadUrl = path+"/common/uploadGroupUserLogo";
		}
		
		$("#"+containerId).kendoUpload({
	        async: {
	            saveUrl: uploadUrl
	        },
	     	multiple: false,      //多选
	      	showFileList: false,  //显示文件列表
	        localization: {
	              select: "请上传图片",
	              cancel: "取消",
	              remove: "移除",  //autoUpload: false
	              retry: "刷新",
	              headerStatusUploading: "上传...",
	              headerStatusUploaded: "上传成功",
	              statusUploading: "loading",
	              statusUploaded: "success",
	              statusFailed: "failed",
	              uploadSelectedFiles: "上传选中的文件",   //autoUpload: false
	        },
	        success: function(e){
	        		if(e.response.code =='0'){
	        			var url = "";
	        			var another_url = "";
	        			if(params.userLevel==3){
	        				url = e.response.result.resultPath;   //图片路径
		    	        	another_url = e.response.result.transpondImagePath;
	        			}else{
	        				url = e.response.result;   //图片路径
	        			}
	    	        	publicService.showUploadImage(imgId,imgUrlId,url);
	    	        	$("#logo_aother_url").val(another_url);
	        		}else if(e.response.code =='1'){
	        			alert(e.response.message);
	        			return;
	        		}

		    },
	        error: function(e){
	        	//alert('失败！');
	        },
	        remove: function(e){
	        	//alert('移除！');
	        },
	        select: function(e){	//选择
	        	var image = e.files[0];
	        	if(limitParam){
	        		if(limitParam.imageSize && image.size>(limitParam.imageSize*1024)){
		        		alert("上传图片的大小请限制在【"+limitParam.imageSize+"Kb】以内！");
		        		e.preventDefault();
		        		return;
		        	}
	        		if(limitParam.format && limitParam.format.indexOf(image.extension.substr(1,image.extension.length).toLowerCase())==-1){
		        		alert("上传图片仅支持【"+limitParam.format+"】格式！");
		        		e.preventDefault();
		        		return;
		        	}
	        	}
	        }
	    });
	};
	
	
	
	$scope.uploadImage("logo","logo_img","logo_url",limitParam);
	publicService.initProvince(1);		//初始化省
	publicService.initCity(1);			//初始化市
	publicService.initArea(1);			//初始化区
	$scope.initMap("map_container","search_location","search_coordinate");		//初始化地图
	publicService.uploadImage("upload1","upload1_img","upload1_url");
	publicService.initAccountState2("checkState");		//初始化【账号状态】2

	

	if(userInfo.user_level==0){	//开发者
		$scope.moduleContainer_show = true;
	}else if(userInfo.user_level==3){	//三级用户
		$scope.logo_show = false;
		$scope.commerce_show = false;
	}else if(userInfo.user_level==2){	//二级用户
		$scope.logo_show = false;
		$scope.commerce_show = false;
	}else if(userInfo.user_level==1){	//一级用户
		
	}
	
	if(params.method=="add"){
		$scope.form.user_level = params.userLevel;
		$scope.form.tag = params.userLabel;
		if(userInfo.user_level==2){
			$scope.form.organization_code = userInfo.organization_code;  //组织编号
//			$('#organization_code').attr("disabled","true");
			var provinceCode = userInfo.userInfoEntity.region_code.split(",")[0];
			//$scope.showDefaultProvince(provinceCode);
		}
		if(params.userLevel==3){
			
		}else if(params.userLevel==2){
			
		}else if(params.userLevel==1){
			$scope.coordinate_show = true;
			$(".otherHide").attr("readonly","readonly");
		}
		$scope.getMenu();		//获取菜单
		$scope.resetPassword_show = false;
	}else if(params.method=="edit"){
		
		$scope.getUserInfo(params.id);
		$scope.form.user_level = params.userLevel;  //当前等级
		if(!params.editPremission){
			$scope.moduleContainer_show = false;
		}
		if(userInfo.user_level==2){
//			$('#organization_code').attr("disabled","true");
		}
	}else if(params.method=="look"){
		$scope.getUserInfo(params.id);
		
		$scope.resetPassword_show = false;
		$scope.submit_show = false;
		$("input").attr("readonly","readonly");
		$('#province').data("kendoComboBox").readonly(true);
		$('#city').data("kendoComboBox").readonly(true);
		$('#area').data("kendoComboBox").readonly(true);
		$('#checkState').data("kendoDropDownList").readonly(true);
	}
	
	

	
});